<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
    <title>Student Website</title>
</head>

<body>
<div class="navbar">
    <span class="title"><a href="/" style="text-decoration: none; color: black">Back To Main Page</a></span>
</div>
<a onclick="window.history.go(-1)">Back</a>
<div class="left">
    <div class="card1">
        <h2>
            <span id="class_title">Loading……</span>
        </h2>
        <p style="font-size: 20px; color: #000000; line-height: 15px; margin-top: 40px;">
            Class introduction
        </p>
        <p id="class_descriptive">Loading……</p>
        <button class="button" style="display: none" id="show_studentList" onclick="searchStuList()">Student List
        </button>
    </div>
</div>
<div class="container">
    <div class="right">
        <div class="card1">
            <h2>
                Homeworks
            </h2>
            <div id="homeworklist">
                <p>
                    Create new homework.
                </p>
            </div>
            <br>
            <button class="button" style="float: right; display: none;" onclick="newHomework()"
                    id="add_new_homework_button">
                Create a new Homework
            </button>
        </div>
    </div>

    <div class="right">
        <div class="card1">
            <h2>
                Courses
            </h2>
            <div id="courselist">
                <p>
                    No more.
                </p>
            </div>
            <br>
            <button class="button" style="float: right; display: none;" onclick="newCoures()"
                    id="add_new_course_button">
                Create a new Course
            </button>
        </div>
    </div>
</div>
<div id="myModal" class="modal">
    <div class="modal-content"  >
        <span class="close">&times;</span>
        <p id="student-list" style="color: black"></p>
    </div>
</div>
</body>

<script>
    const urlParams = new URLSearchParams(window.location.search);
    const classname = urlParams.get('classname');
    console.log(classname)
    const add_new_homework_button = document.getElementById("add_new_homework_button");
    const add_new_course_button = document.getElementById("add_new_course_button");
    const show_studentList_button = document.getElementById("show_studentList");
    let username;

    fetch(`/api/class?classname=${classname}`, {
        method: 'GET',
    })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Failed to get class');
            }
        })
        .then(classResponse => {
            var classData = classResponse.data;

            if (classData == null) {
                window.location.href = "/404";
            }
            var matchedRow = classData.find(row => row[0] === classname);

            if (matchedRow) {
                document.getElementById("class_title").innerHTML = matchedRow[0];
                document.getElementById("class_descriptive").innerHTML = matchedRow[1];
            } else {
                window.location.href = "/404";
            }
            return fetch(`/api/course?classname=${classname}`, {
                method: 'GET',
            });
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Failed to get course');
            }
        })
        .then(courseResponse => {
            const data = courseResponse.data;
            console.log(data);

            const courselist = document.getElementById('courselist');
            courselist.innerHTML = '';

            data.forEach(courseInfo => {
                const courseItem = document.createElement('div');
                courseItem.className = 'course-item';
                courseItem.innerHTML = `
               <div style="border: 5px solid #ccc; border-radius: 10px;padding: 10px; background-color: #F9F2E0;">
                    <h3>${courseInfo[0]}</h3>
                    <p style="line-height: 20px; font-weight: 900;">State ${courseInfo[6] == -1 ? "<span style='color: #d42d26;'>Didn't start</span>" : (courseInfo[6] == 0 ? "<span style='color: #479ee4;'>Toward</span>" : "<span style='color: #44984e;'>Closed</span>")}</p>
                    <p style="line-height: 20px;">Teacher<br><span id="teacherName"">${courseInfo[2]}</span></p>
                    <p style="line-height: 20px;">Description<br>${truncateString(courseInfo[3])}</p>
                    <p style="line-height: 20px;">Begin<br>${courseInfo[4]}</p>
                    <p style="line-height: 20px;">End<br>${courseInfo[5]}</p>
                    <button class="button" onclick="window.location.href = '/forum?courseId=${courseInfo[7]}'">Forum</button>
                    <button class="button" onclick="nextCourseState('${courseInfo[0]}')" type="uptype">${courseInfo[6] == -1 ? "Start" : "Closed"}</button>
                    <button class="button" onclick="deleteCourse('${courseInfo[0]}')" type="uptype">Delete</button>
                    <button class="button" type="add_lec" onclick="window.location.href = '/course_content?courseId=${courseInfo[7]}'">Add new Lecture</button>
                </div>
            `;

                courselist.appendChild(courseItem);
            });

            if (data.length === 0) {
                const noMoreCourses = document.createElement('div');
                noMoreCourses.style = "text-align: center;";
                courselist.appendChild(noMoreCourses);
            }

            return fetch(`/api/homeworks?classname=${classname}`, {
                method: 'GET',
            });
        })
        .then(response => {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error('Failed to get homeworks');
            }
        })
        .then(homeworkResponse => {
            const data = homeworkResponse.data;
            console.log(data);

            const homeworklist = document.getElementById('homeworklist');
            homeworklist.innerHTML = '';

            data.forEach(homeworkInfo => {
                const homeworkItem = document.createElement('div');
                homeworkItem.className = 'homework-item';

                homeworkItem.innerHTML = `
                    <div style="border: 5px solid #ccc; border-radius: 10px;padding: 10px; background-color: #F9F2E0;>"
                        <h3>${homeworkInfo[1]}</h3>
                        <p style="color: black">${truncateString(homeworkInfo[2])}</p>
                        <p style="color: black">Start At<br><div style="color: black">${homeworkInfo[3]}</div></p>
                        <p style="color: black">Deadline<br><div style="color: black">${homeworkInfo[4]}</div></p>
                        <button class="button" onclick="view('${homeworkInfo[1]}')">Detail</button>
                        <button class="button" onclick="deleteHomework('${homeworkInfo[1]}')" type="uptype">Delete</button>
                    </div>
                `;

                homeworklist.appendChild(homeworkItem);
            });

            if (data.length === 0) {
                const noMoreHomeworks = document.createElement('div');
                noMoreHomeworks.style = "text-align: center;";
                homeworklist.appendChild(noMoreHomeworks);
            }

            fetch('/api/get_user_name')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.text();
                })
                .then(data => {
                    username = data;

                    fetch(`/api/users/${username}`, {
                        method: 'GET',
                    })
                        .then(response => {
                            if (response.ok) {
                                return response.json();
                            } else {
                                throw new Error('Failed to get user data');
                            }
                        })
                        .then(userinfo_data => {
                            console.log(userinfo_data);
                            if (userinfo_data.data[2] === "0" || userinfo_data.data[2] === "1") {
                                const uptype = document.querySelectorAll('[type="uptype"]');
                                uptype.forEach(element => {
                                    element.parentNode.removeChild(element);
                                });
                            }
                            if (userinfo_data.data[2] === "0" || userinfo_data.data[2] === "2") {
                                const add_lec = document.querySelectorAll('[type="add_Lec"]');
                                add_lec.forEach(element => {
                                    element.parentNode.removeChild(element);
                                })
                            }
                            if (userinfo_data.data[2] != "0") { // 1老师
                                add_new_homework_button.style.display = "block";
                                show_studentList_button.style.display = "block";
                                if (userinfo_data.data[2] != "1") { // 2 管理员
                                    add_new_course_button.style.display = "block";
                                }
                            }

                            getPosts(courseId);
                        })
                        .catch(error => {
                            console.error('Error:', error);
                        });
                })
                .catch(error => {
                    console.error('There was a problem with the fetch operation:', error);
                });
        })

    function deleteHomework(homeworkName) {
        const isConfirmed = confirm(`Are you sure you want to delete the job "${homeworkName}"?`);

        if (isConfirmed) {
            fetch(`/api/homeworks`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    homeworkname: homeworkName,
                    classname: classname
                })
            })
                .then(response => {
                    if (response.ok) {
                        window.location.reload();
                    } else {
                        throw new Error(`Failed to delete homework "${homeworkName}".`);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        } else {
            console.log(`取消删除作业 "${homeworkName}"`);
        }
    }

    function deleteCourse(courseName) {
        const isConfirmed = confirm(`Are you sure you want to delete the course "${courseName}"?`);

        if (isConfirmed) {
            fetch(`/api/course`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    coursename: courseName
                })
            })
                .then(response => {
                    if (response.ok) {
                        window.location.reload();
                    } else {
                        throw new Error(`Failed to delete homework "${courseName}".`);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        } else {
            console.log(`取消删除讲座 "${homeworkName}"`);
        }
    }

    function nextCourseState(courseName) {
        fetch(`/api/course`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                coursename: courseName
            })
        })
            .then(response => {
                if (response.ok) {
                    window.location.reload();
                } else {
                    throw new Error(`Failed to delete homework "${courseName}".`);
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    }

    function searchStuList() {
        const url = `/api/studentList?class=${classname}`;
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                displayStudentList(data); // 显示学生列表
            })
            .catch(error => {
                console.error('There was an error:', error);
            });
    }

    function formatData(data) {
        let formatted = data.map(item => `ID: ${item.id}, Name: ${item.name}`).join('\n');
        return formatted;
    }

    function displayStudentList(students) {
        const listElement = document.getElementById('student-list');
        const modal = document.getElementById('myModal');
        const span = document.getElementsByClassName('close')[0];

        listElement.innerHTML = '';
        students.forEach(student => {
            listElement.innerHTML += `ID: ${student.id}, Name: ${student.name}<br><hr>`;
        });

        modal.style.display = "block";

        span.onclick = function () {
            modal.style.display = "none";
        }

        window.onclick = function (event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
    }


    function newCoures() {
        window.location.href = `/newcourse?classname=${classname}`;
    }

    function newHomework() {
        window.location.href = `/newhomework?classname=${classname}`;
    }

    function view(homeworkname) {
        window.location.href = `/homework?classname=${classname}&homeworkname=${homeworkname}`;
    }

    function truncateString(str) {
        if (str.length > 15) {
            return str.slice(0, 15) + '...';
        } else {
            return str;
        }
    }
</script>
<style>
    .container {
        display: flex;
        width: 100%;
    }

    .left {
        /* 可以根据需要自定义样式，比如宽度、背景色等 */
        overflow: auto;
    }

    .right {
        flex: 4;
        overflow: auto;
    }

    #homeworklist p {
        color: #6c757d; /* 灰色文本 */
    }

    .card1 {
        border-radius: 20px;
        background-color: #1660AB;
        margin: 20px 5%;
        padding: 15px 30px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .modal {
        display: none;
        position: fixed;
        z-index: 1;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0, 0, 0, 0.4);
    }

    .modal-content {
        background-color: #1660AB;
        margin: 15% auto;
        padding: 20px;
        border: 1px solid #888;
        width: 80%;
        border-radius: 10px;
    }

    .close {
        color: #aaa;
        float: right;
        font-size: 28px;
        font-weight: bold;
    }

    .close:hover,
    .close:focus {
        color: black;
        text-decoration: none;
        cursor: pointer;
    }

</style>

</html>